qinglan.Canvas.CanvasRender = qinglan.Canvas.Class(function() {

}).statics({
	drawRect: function(ctx, x0, y0, x1, y1, color) {
		x0 = Math.floor(x0);
		y0 = Math.floor(y0);
		x1 = Math.floor(x1);
		y1 = Math.floor(y1);
		ctx.lineWidth = 2;
		ctx.strokeStyle = color.getColorString();
		ctx.strokeRect(x0, y0, x1 - x0, y1 - y0);
	},
	drawFilledRect: function(ctx, x0, y0, x1, y1, color, color2) {
		ctx.save();
		if (color2 != undefined) {
			var gradient = ctx.createLinearGradient(0, y0, 0, y1);
			gradient.addColorStop(0, color.getColorString());
			gradient.addColorStop(1, color2.getColorString());
			ctx.fillStyle = gradient;
		} else {
			ctx.fillStyle = color.getColorString();
		}

		ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
		ctx.restore();
	},
	drawLine: function(ctx, x0, y0, x1, y1, color) {
		x0 = Math.floor(x0);
		y0 = Math.floor(y0);
		x1 = Math.floor(x1);
		y1 = Math.floor(y1);
		ctx.lineWidth = 2;
		ctx.strokeStyle = color.getColorString();
		ctx.beginPath();
		ctx.moveTo(x0, y0);
		ctx.lineTo(x1, y1);
		ctx.stroke();
		ctx.moveTo(0, 0);
	},
	drawCircle: function(ctx, x, y, r, color) {
		ctx.lineWidth = 2;
		ctx.strokeStyle = color.getColorString();
		ctx.beginPath();
		ctx.arc(x, y, r, 0, Math.PI * 2, true);
		ctx.stroke();
	},
	// 纯文本
	drawSystemText: function(ctx, txt, x, y, color) {
		ctx.textAlign = 'left';
		ctx.fillStyle = color.toString();
		ctx.fillText(txt, x, y);
	},
	drawImage: function(ctx, img, offsetx, offsety, viewx, viewy, positionx, positiony, width, height) {
		if (!img.complete) return;
		ctx.drawImage(img, offsetx, offsety, viewx, viewy, positionx, positiony, width, height);
	},
	// clear canvas
	// 如果指定了color，则在clear画布之后加上颜色
	clear: function(ctx, width, height, color) {
		ctx.clearRect(0, 0, width, height); !! color && qinglan.Canvas.CanvasRender.drawFilledRect(ctx,0, 0, width, height, color);
	},
	drawSprite: function(ctx, sprite) {
		if (!sprite.visible) {
			return false;
		}
		ctx.save();
		sprite.alpha > 0 && 1 != sprite.alpha && (ctx.globalAlpha *= sprite.alpha);
		(sprite.position.x || sprite.position.y) && ctx.translate(sprite.position.x, sprite.position.y);

		(sprite.scaleX != 1 || sprite.scaleY != 1) && ctx.scale(sprite.scaleX, sprite.scaleY);
		sprite.rotation % 360 && (ctx.rotate((sprite.rotation % 360) * qinglan.Canvas.Const.DEG_TO_RAD));
		
		if(!sprite.shadowColor.isAlphaZero()){
			ctx.shadowColor = sprite.shadowColor.getColorString();
			ctx.shadowOffsetX = sprite.shadowOffsetX;
			ctx.shadowOffsetY = sprite.shadowOffsetY;
			ctx.shadowBlur = sprite.shadowBlur;
		}
 
		sprite.translateCenter && ctx.translate(-sprite.width / 2, -sprite.height / 2);

		sprite.draw(ctx);
		ctx.restore();
	}
});
